package org.spring.autoType.config;

import org.spring.autoType.service.ProcessorAdapter;
import org.spring.autoType.target.TypeTarget;
import org.spring.autoType.utils.Constant;
import org.spring.autoType.utils.TypeEnum;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author LHB
 * @date 2019/12/24 14:17
 */
@Component
@ConditionalOnBean
public class AutoTypeConfigure implements ApplicationContextAware {
    /**
     * 加入spring容器
     */
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 从spring容器中获取需要的注解类
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //过滤bean
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(TypeTarget.class);
        if (beans != null && beans.size() > 0) {
            for (Object serviceBean : beans.values()) {
                //获取bean类型值
                TypeEnum payType = serviceBean.getClass().getAnnotation(TypeTarget.class).value();
                Constant.classMap.put(payType.getName(), serviceBean.getClass());
            }
        }


    }

    /**
     * 获取处理适配器
     *
     * @param payType
     * @return
     */
    public ProcessorAdapter getAdapter(String payType) throws Exception {
        Class adapter = Constant.classMap.get(payType);
        if (adapter == null) {
            throw new Exception("无此适配器");
        }

        return (ProcessorAdapter) applicationContext.getBean(adapter);

    }
}
